using System;
using System.Data;
using System.Data.Common;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text.RegularExpressions;

namespace Tilver.DBConnectionUI
{
    internal class DbProvidersCollection
    {
        Dictionary<string, DbProvider> _providers;
        public DbProvidersCollection()
        {
            _providers = new Dictionary<string, DbProvider>();
            DataTable dataProvidersTable = DbProviderFactories.GetFactoryClasses();
            foreach (DataRow row in dataProvidersTable.Rows)
            {
                DbProvider provider = new DbProvider(row);
                if(!_providers.ContainsKey(provider.InvariantName))
                    _providers.Add(provider.InvariantName, provider);
            }
        }

        public DbProvider this[string invariantName]
        {
            get
            {
                if (_providers.ContainsKey(invariantName))
                    return _providers[invariantName];
                return null;
            }
        }

        public void Add(DbProvider provider)
        {
            if (!_providers.ContainsKey(provider.InvariantName))
                _providers.Add(provider.InvariantName, provider);
        }

        public void Clear()
        {
            _providers.Clear();
        }

        /// <summary>
        /// Returns an array of filtered DataProviders
        /// </summary>
        public DbProvider[] AvailableProviders
        {
            get
            {
                bool isFiltered = ConnectionStringDialog.Filters.Count > 0;
                List<DbProvider> result = new List<DbProvider>();
                foreach (DbProvider provider in _providers.Values)
                {
                    if (isFiltered)
                    {
                        if (ConnectionStringDialog.FilterMode == FilterMode.Exclude)
                        {
                            if (!ConnectionStringDialog.Filters.Contains(provider.InvariantName))
                                result.Add(provider);
                        }
                        else
                        {
                            if (ConnectionStringDialog.Filters.Contains(provider.InvariantName))
                                result.Add(provider);
                        }
                    }
                    else
                        result.Add(provider);
                }
                return result.ToArray();
            }
        }
    }
}
